package com.dynamo.transport.network.practise.bio;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.Socket;

/**
 * @author duanyimiao
 * @create 2018-10-27 8:35 PM
 * @description
 **/
public class SocketThread extends Thread {
    private Socket socket;
    private ChannelHandler channelHandler;

    public SocketThread(Socket socket, ChannelHandler channelHandler) {
        this.socket = socket;
        this.channelHandler = channelHandler;
    }

    @Override
    public void run() {
            try {
                InputStream in = socket.getInputStream();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] bytes = new byte[4096];
                int n = -1;
                //如果没有数据可以读，线程一直阻塞在read方法上
                //如果两个请求发送字节很多时，这个时候为了网络高效传输和将其两个请求合并成一个，因此接受到数据就是两个请求合并起来的整个字符串，所以需要定义一个分割符，以此为一个请求串
              //  while (-1 != (n = in.read(bytes))) {
                while(-1 != (n=in.read())){
                    bos.write(n);
                    //以换行符为标识为一个请求
                    if(n == '\n') {
                        channelHandler.channelRead(bos.toByteArray(), socket);
                        bos.reset();
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
}
